import { ElMessage } from 'element-plus';
import { useProductApi } from '/@/api/product';
import { useCouponApi } from '/@/api/coupon';
import { useFileApi } from '/@/api/file';

const { getProdSkuList, mulCancelNew, getGoodsTagList } = useProductApi();
const { getProdTemp, getQATemp, exportProdByIdList } = useFileApi();
const { getCouponList } = useCouponApi();

export const currencyMap = {
	US: ['usPriceStart', 'usPriceEnd'],
	UK: ['ukPriceStart', 'ukPriceEnd'],
	EU: ['euPriceStart', 'euPriceEnd'],
};

export const state = reactive({
	showHomePage: true,
	isOffShelves: false,
});
export const useInit = () => {
	const router = useRouter();
	const isAdd = ref(false);
	const addDialogVisible = ref(false);
	const tableData = ref([]);
	const prodInfo = ref({});
	const searchForm = ref({
		tagId: '',
	});

	const page = () => {
		return {
			pageSize: 10,
			current: 1,
			total: 0,
		};
	};

	const ipage = ref(page());
	const tpage = ref(page());
	//检测价格区间是否合法
	const diffPrice = () => {
		if (searchForm.value.priceStart && searchForm.value.priceEnd) {
			if (searchForm.value.priceStart > searchForm.value.priceEnd) {
				const cache = searchForm.value.priceStart;
				searchForm.value.priceStart = searchForm.value.priceEnd;
				searchForm.value.priceEnd = cache;
			}
		}
	};
	//设置币种
	const setCurrency = () => {
		//清空上一次搜索的数据
		searchForm.value.usPriceStart = undefined;
		searchForm.value.usPriceEnd = undefined;
		searchForm.value.ukPriceStart = undefined;
		searchForm.value.ukPriceEnd = undefined;
		searchForm.value.euPriceStart = undefined;
		searchForm.value.euPriceEnd = undefined;
		const { currency, priceStart, priceEnd } = searchForm.value;
		if (!searchForm.value.priceStart && !searchForm.value.priceEnd) return;
		if (!currency) {
			//默认设置为美元
			searchForm.value.usPriceStart = priceStart;
			searchForm.value.usPriceEnd = priceEnd;
		} else {
			searchForm.value[currencyMap[currency][0]] = priceStart;
			searchForm.value[currencyMap[currency][1]] = priceEnd;
		}
	};

	const init = async (option) => {
		diffPrice();
		setCurrency();
		if (state.isOffShelves) searchForm.value.publishStatus = 0; //下架页面设置参数
		searchForm.value.tagId = option.tagId ? option.tagId : searchForm.value.tagId;
		let res = await getProdSkuList({ ...searchForm.value, ...ipage.value });
		if (res.code === 200) {
			const { data, total } = res.data;
			let tbData;
			tbData = data.map((item) => {
				item.isSort = false;
				return item;
			});
			tableData.value = tbData;
			ipage.value.total = total;
		}
	};

	const tagList = ref([]);
	const geiTagList = async () => {
		let res = await getGoodsTagList({ ...tpage.value });
		console.log(res);
		if (res.code === 200) {
			tagList.value = res.data.data;
		}
	};

	return {
		searchForm,
		isAdd,
		prodInfo,
		addDialogVisible,
		tableData,
		ipage,
		tagList,
		page,
		init,
		toAdd() {
			isAdd.value = true;
			state.showHomePage = false;
			// const name = state.isOffShelves ? 'offShelvesAddProd' : 'AddProd';
			router.push({ name: 'ProductAddProduct' });
		},
		geiTagList,
	};
};
//优惠券列表数据
export const useCouponList = () => {
	const couponList = ref([]);
	async function getCoupinList() {
		let params = {
			current: 1,
			pageSize: 999,
		};
		let res = await getCouponList(params);
		if (res.code !== 200) return;
		couponList.value = res.data.data;
	}
	onMounted(getCoupinList);
	return {
		couponList,
	};
};

export const useWatchRoute = (init) => {
	const route = useRoute();
	watch(
		route,
		({ name }) => {
			console.log(name);
			state.isOffShelves = name === 'OffShelves';
			state.showHomePage = name === 'ProdList' || state.isOffShelves;
			if (state.showHomePage) init();
		},
		{ immediate: true }
	);
	return {};
};

export const useFile = (multipleSelection) => {
	return {
		exportQATemp() {
			getQATemp().then((response) => {
				const url = window.URL.createObjectURL(new Blob([response]));
				const link = document.createElement('a');
				link.href = url;
				link.setAttribute('download', '商品问答模板.xls');
				document.body.appendChild(link);
				link.click();
			});
		},
		exportProdTemp() {
			getProdTemp().then((response) => {
				const url = window.URL.createObjectURL(new Blob([response]));
				const link = document.createElement('a');
				link.href = url;
				link.setAttribute('download', '商品模板.xls');
				document.body.appendChild(link);
				link.click();
			});
		},
		uploadFile() {
			// const param = new FormData();
			// param.append("file", file.file);
			// const config = {
			//     headers: { "Content-Type": "multipart/form-data" },
			// };
			// axios.post("/admin/excel/addProduct", param, config).then((res) => {
			//     console.log(res);
			// });
		},
		exportProd() {
			const params = {
				idList: multipleSelection.value.map((item) => item.productId),
				type: 2,
			};
			exportProdByIdList(params).then((response) => {
				const url = window.URL.createObjectURL(new Blob([response]));
				const link = document.createElement('a');
				link.href = url;
				link.setAttribute('download', '商品列表.xls');
				document.body.appendChild(link);
				link.click();
			});
			console.log('exportProd');
			// console.log(multipleSelection.value);
			// let res = await exportProdByIdList();
		},
	};
};

export const useNewProd = (init, multipleSelection) => {
	return {
		async cancelNew() {
			const idList = [];
			multipleSelection.value.forEach(({ productId }) => {
				if (!idList.includes(productId)) idList.push(productId);
			});
			let res = await mulCancelNew(idList);
			if (res.code !== 200) return;
			ElMessage.success('修改成功！');
			init();
		},
	};
};
